#!/usr/bin/perl

die "\nUsage:\n\tcount_by_node_length.pl <nodelength> <tax1_identifier> <tax2_identifier> file1 [file2..]\n\n" unless @ARGV >=4;
my $node_len = shift @ARGV;
my $tax1 = shift @ARGV;
my $tax2 = shift @ARGV;
my @FILES = @ARGV;
for my $file(@FILES)
{
	{
		@ARGV = $file;
		my @lines;
		my %counts;
		while (<>)
		{
			chomp;
			my @genes = split /\t/;
			if (!@genes)
			{
				push(@lines, $_."\n");
				next;
			}
			my $cnt_tax1 = 0;
			my $cnt_tax2 = 0;
			my @gene_names;
			for (@genes)
			{
				my ($gene_name, $len) = split /:/;
				die unless defined $len;
				next unless $len <= $node_len;
				if ($gene_name =~ m/$tax1/)
				{
					++$cnt_tax1;
				}
				elsif ($gene_name =~ m/$tax2/)
				{
					++$cnt_tax2;
				}
				else
				{
					die "What is this??? <$gene_name> in [$file]\n";
				}
				push(@gene_names, $gene_name);
			}
			--$cnt_tax1 if ($cnt_tax1 > 0);
			--$cnt_tax2 if ($cnt_tax2 > 0);
			$counts{$cnt_tax1}{$cnt_tax2}++;
			print "$cnt_tax1\t$cnt_tax2\t$counts{$cnt_tax1}{$cnt_tax2}\t", join(" ", @gene_names),"\n"
				if ($cnt_tax1 || $cnt_tax2);
		}
		print "$file contained:\n$tax1\t$tax2:\n";
		for my $tax1_cnts(sort {$a <=> $b} keys %counts)
		{
			for my $tax2_cnts(sort {$a <=> $b}
				keys %{$counts{$tax1_cnts}})
			{
				next if ($tax1_cnts + $tax2_cnts == 0);
				print $tax1_cnts ? "$tax1_cnts\t" : "\t";
				print $tax2_cnts ? "$tax2_cnts\t" : "\t";
				print "$counts{$tax1_cnts}{$tax2_cnts}\n";
			}
		}
		print "\n";
	}
}
